package cn.controller;

import cn.common.ConfigOption;
import cn.common.ExceResult;
import cn.common.GridCommon;
import cn.common.LayTable;
import cn.filter.LoginCheck;
import cn.kpi.common.Excel.domain.SubheadModel;
import cn.kpi.common.Excel.export.ExportConfigFactory;
import cn.kpi.common.Excel.export.FileExportor;
import cn.kpi.common.Excel.export.domain.common.ExportConfig;
import cn.kpi.common.Excel.export.domain.common.ExportResult;
import cn.kpi.entity.attendance.AttSummaryEntity;
import cn.kpi.entity.attendance.AttTbBatchEntity;
import cn.kpi.entity.payassessment.*;
import cn.kpi.entity.sys.Configure;
import cn.kpi.entity.sys.OrgEntity;
import cn.kpi.entity.sys.UserEntity;
import cn.kpi.service.attendance.IAttBmHzService;
import cn.kpi.service.attendance.IAttFjGdService;
import cn.kpi.service.common.IOrgSummaryService;
import cn.kpi.service.payassessment.IPayAssessmentService;
import cn.kpi.service.sys.IConfigureService;
import cn.kpi.service.sys.IOrgService;
import cn.kpi.service.sys.IUserService;
import org.joda.time.MonthDay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

import static cn.kpi.common.utils.DateUtils.*;

@Controller
@RequestMapping("paytrans")
public class PayTransController extends BaseController {

    @Autowired
    private IOrgService iOrgService;


    @Autowired
    private IConfigureService configureService;
    @Autowired
    private IPayAssessmentService iPayAssessmentService;

    @Autowired
    private IOrgSummaryService iOrgSummaryService;

    @Autowired
    private IUserService iUserService;

    //region 交通补助
    //初始化
    @RequestMapping(value = "/trans_pay_dept")
    public String tranPayDepttList(Model model) {
        try {
//            List<OrgEntity> orglst = getOrgEntitiesAll();//getOrgEntities();//按权限暂时取掉
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH) + 1;
//            String title = orglst.get(0).getOrgname()+year+"年"+month+"月交通补助表";
//            model.addAttribute("orglst", orglst);
//            model.addAttribute("title",title);
            model.addAttribute("year", year);
            model.addAttribute("month", month);
            model.addAttribute("type", 0);
        } catch (Exception ex) {
        }
        return "payassessment/trans_pay_dept";
    }


    @RequestMapping(value = "/pdf")
    public String pdf(Model model) {
        try {
//            List<OrgEntity> orglst = getOrgEntitiesAll();//getOrgEntities();//按权限暂时取掉
            UserEntity user = this.GetLoginUser();
            model.addAttribute("orgname", user.getOrgname());
        } catch (Exception ex) {
        }
        return "payassessment/trans_show_pdf";
    }


    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_org_tran_dept_list")
    public LayTable<Map> GetOrgTranDeptList(HttpServletRequest request) {

        List<Map> lst = null;
        LayTable<Map> layTable = new LayTable<Map>();
        try {
            int year = Integer.parseInt(request.getParameter("year"));
            int month = Integer.parseInt(request.getParameter("month"));

            Calendar cal = Calendar.getInstance();
            int currentyear = cal.get(Calendar.YEAR);
            int currentmonth = cal.get(Calendar.MONTH) + 1;
            if (currentyear != year) {
                currentmonth = 12;
            }


            Integer iexit = iOrgSummaryService.GetOrgYearCount("tran", year, 0);
            if (iexit == 0) {
                List<Integer> list = new ArrayList<Integer>();
                for (int i = 0; i < 12; i++) {
                    list.add(i + 1);
                }
                iOrgSummaryService.InsertOrgYearTranBacth(list, year);
            }

            String where = "";
            where += " AND orgid IN (" + this.GetOrgListByRole() + ")";
            lst = iOrgSummaryService.GetOrgSummaryTranList(where, year, month, "", currentmonth);

            layTable.setCode(0);
            layTable.setCount(lst.size());
            layTable.setData(lst);

        } catch (Exception e) {
            e.printStackTrace();
            layTable.setCode(500);
        }
        return layTable;
    }


    @RequestMapping(value = "/trans_pay")
    public String TranList(Model model) {
        try {
            UserEntity loginUser = this.GetLoginUser();
            if (loginUser.getRealname().contains("开发")) {
                model.addAttribute("isadmin", true);
            } else {
                model.addAttribute("isadmin", false);
            }

            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH)+1;

            model.addAttribute("year", year);
            model.addAttribute("month", month);
            //System.out.println(year+" "+month);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "payassessment/trans_pay";
    }


    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_org_tran_list")
    public GridCommon<Map> GetOrgTranList(HttpServletRequest request) {

        List<Map> lst = null;
        GridCommon<Map> countlist = new GridCommon<Map>();
        try {
            int year = Integer.parseInt(request.getParameter("year"));
            int month = Integer.parseInt(request.getParameter("month"));
            String strorgid = request.getParameter("orgid");
            String strstatus = request.getParameter("status");
            String where = "";
            if (this.GetOrgListByRole() != "")
                where += " AND orgid IN (" + this.GetOrgListByRole() + ")";

            Calendar cal = Calendar.getInstance();
            int currentyear = cal.get(Calendar.YEAR);
            int currentmonth = cal.get(Calendar.MONTH) + 1;
            if (currentyear != year) {
                currentmonth = 12;
            }

            if (strorgid != null && strorgid.length() > 0) {
                OrgEntity orgentity = iOrgService.GetOrgById(Long.parseLong(strorgid));
                where += " AND orgid IN ( SELECT orgid FROM t_sys_org WHERE lft>=" + orgentity.getLft() + " AND lft<="
                        + orgentity.getRgt() + ")";
            }

            Integer iexit = iOrgSummaryService.GetOrgYearCount("tran", year, 0);
            if (iexit == 0) {
                List<Integer> list = new ArrayList<Integer>();
                for (int i = 0; i < 12; i++) {
                    list.add(i + 1);
                }
                iOrgSummaryService.InsertOrgYearTranBacth(list, year);
            }

            lst = iOrgSummaryService.GetOrgSummaryTranList(where, year, month, strstatus, currentmonth);
//            lst = iOrgSummaryService.GetOrgSummaryList(where, year, month, strstatus, currentmonth);
            countlist.setCurrentPage(1);
            countlist.setPageSize(10);
            countlist.setItems(lst);
            countlist.setStatus(0);
            countlist.setMsg("");
            countlist.setCountRecord(lst.size());

        } catch (Exception e) {
            e.printStackTrace();
            countlist.setCurrentPage(1);
            countlist.setPageSize(10);
            countlist.setItems(null);
            countlist.setStatus(1);
            countlist.setMsg("操作成功");
        }
        return countlist;
    }


    //交通补助生成
    @ResponseBody
    @RequestMapping(value = "/create_tran_pay")
    public ExceResult CreateAttTbNoDetail(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String strorgid = request.getParameter("orgid");
            String stryear = request.getParameter("year");
            String strmonth = request.getParameter("month");

            Long orgid = Long.parseLong(strorgid);
            Long byuserid = this.GetLoginUserId();
            UserEntity byuser = this.GetUserById(byuserid);
            int year = Integer.parseInt(stryear);
            int month = Integer.parseInt(strmonth);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(sdf.parse(year + "-" + month + "-1"));
            int countday = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            AttTbBatchEntity entity = new AttTbBatchEntity();
            entity.setByuserid(byuserid);
            entity.setDay(0);
            entity.setDays(countday);
            entity.setMonth(month);
            entity.setOrgid(orgid);
            entity.setYear(year);
            switch (month) {
                case 1:
                case 2:
                case 3:
                    entity.setQuarter(1);
                    break;
                case 4:
                case 5:
                case 6:
                    entity.setQuarter(2);
                    break;
                case 7:
                case 8:
                case 9:
                    entity.setQuarter(3);
                    break;
                case 10:
                case 11:
                case 12:
                    entity.setQuarter(4);
                    break;
            }

            int iResult = 0;
            int iExit = iOrgSummaryService.GetExitOrgSummary(orgid, year, month, "tran");
            //System.out.println(iExit+" "+orgid+" "+year+" "+month);
            if (iExit > 0) {
                result.setCode(400);
                result.setResult(iExit);
                result.setMsg("该机构该年度该月已生成补助(" + year + "年" + month + "月)");
                return result;
            }

            int isExit = iOrgSummaryService.GetExitOrgStatusSummary(orgid, year, month, "att", "2");//是否已经归档
            //System.out.println(iExit+" "+orgid+" "+year+" "+month);
            if (isExit == 0) {
                result.setCode(400);
                result.setResult(iExit);
                result.setMsg("考勤还未归档，请稍后填报！");
                return result;
            }


            List<OrgEntity> orgEntities = new ArrayList<>();
            String orgs = "";
            String where = "";
            orgEntities = GetOrgListByOrgid(orgid);

            for (OrgEntity orgEntity : orgEntities) {
                if (orgs.equals(""))
                    orgs = String.valueOf(orgEntity.getOrgid());
                else
                    orgs += "," + orgEntity.getOrgid();
            }

            if (orgs.length() > 0) {
                where += " AND userid IN (SELECT userid FROM t_sys_user WHERE szdw in (" + orgs + "))";
            }

            //11.1平时考核
            where += " AND userstatus='在职'";
            List<UserEntity> userlst = iUserService.GetUserListTranByWhere(where, stryear, strmonth);

            //取出交通补助规则
            AssessRulePay assessRulePay = iPayAssessmentService.getAssessRuleByCode("jtbt");
            Float fullmoney = assessRulePay.getFullMoney() != null ? Float.valueOf(assessRulePay.getFullMoney()) : 660f;
            Float vacaSum = assessRulePay.getFallVacaSum() != null ? Float.valueOf(assessRulePay.getFallVacaSum()) : 30f;
            Float materSum = assessRulePay.getMatterVacaSum() != null ? Float.valueOf(assessRulePay.getMatterVacaSum()) : 30f;

            List<TransportationPayVoEntity> lst = new ArrayList<>();
            for (UserEntity userEntity : userlst) {
                if (userEntity.getUserstatus().equals("在职")) {
                    Float FallVaca = userEntity.getFallVaca() != null ? userEntity.getFallVaca() : 0f;
                    Float Matter = userEntity.getFallVaca() != null ? userEntity.getMatterVaca() : 0f;
                    TransportationPayVoEntity payVoEntity = new TransportationPayVoEntity();
                    payVoEntity.setMonth(strmonth);
                    payVoEntity.setYear(stryear);
                    payVoEntity.setCardno(userEntity.getCardno());
                    payVoEntity.setUserid(userEntity.getUserid());
                    payVoEntity.setRsgxszdw(userEntity.getRsgxszdw());
                    payVoEntity.setRsgxszdwname(userEntity.getRsgxorgname());
                    payVoEntity.setOrgid(userEntity.getSzdw());
                    payVoEntity.setOrgname(userEntity.getOrgname());
                    payVoEntity.setUserstatus(userEntity.getUserstatus());
                    payVoEntity.setRealname(userEntity.getRealname());
                    payVoEntity.setOriginMoney(fullmoney);
                    Float lostmoney = vacaSum * FallVaca + materSum * Matter;
                    if(lostmoney>=660f) lostmoney = 660f;//最多扣660
                    payVoEntity.setLostMoney(lostmoney);
                    payVoEntity.setNowMoney(payVoEntity.getOriginMoney() - payVoEntity.getLostMoney());
                    payVoEntity.setStatus(0);
                    payVoEntity.setByuserid(byuser.getUserid());
                    payVoEntity.setByuserrsgxszdw(byuser.getRsgxszdw());
                    payVoEntity.setByuserrsgxszdwname(byuser.getRsgxorgname());
                    payVoEntity.setByuserszdw(byuser.getSzdw());
                    payVoEntity.setByuserszdwname(byuser.getOrgname());
                    payVoEntity.setByuseruserstatus(byuser.getUserstatus());
                    lst.add(payVoEntity);
                }
            }

//            entity.setDays(qqtsset);

            iResult = iPayAssessmentService.createTrancePayList(entity, lst);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
                result.setData(orgid.toString());
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
            ex.printStackTrace();
        }
        return result;
    }


    //交通补助获取
    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_tran_dept_list")
    public LayTable<TransportationPayVoEntity> GetSummaryList(HttpServletRequest request) {
        LayTable<TransportationPayVoEntity> layTable = new LayTable<TransportationPayVoEntity>();
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            String year = request.getParameter("year");
            String month = request.getParameter("month");
            String orgid = request.getParameter("orgid");
            String orgsummaryid = request.getParameter("orgsummaryid");
            String realname = request.getParameter("realname");

            String orgs = "";
            List<OrgEntity> orgEntities = new ArrayList<>();
            orgEntities = GetOrgListByOrgid(Long.valueOf(orgid));

            for (OrgEntity orgEntity : orgEntities) {
                if (orgs.equals(""))
                    orgs = String.valueOf(orgEntity.getOrgid());
                else
                    orgs += "," + orgEntity.getOrgid();
            }

            String where = "";
            String countWhere = "";
            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (month != null && month.length() > 0) {
                where += " AND mouth=" + month;
            }

            if (orgs.length() > 0) {
                where += " AND orgid IN (" + orgs + ")";
            }

            if (orgsummaryid != null && orgsummaryid.length() > 0 && !orgsummaryid.equals("0")) {
                where += " AND orgsummaryid=" + orgsummaryid;
            }

            if (realname != null && realname.length() > 0) {
                where += " AND userid IN (SELECT userid FROM t_sys_user WHERE cardno LIKE '%" + realname + "%'  or realname LIKE '%" + realname + "%')";
            }

            countWhere = where;
            int beginrow = (page - 1) * limit;
            int endrow = limit;

            where += " LIMIT " + beginrow + "," + endrow;
            List<TransportationPayVoEntity> lst = iPayAssessmentService.getTranPayVoEntity(where);
            for (int i = 0; i < lst.size(); i++) {
                int rownum = (page - 1) * limit + (i + 1);
                lst.get(i).setRowNum(rownum);
            }

            int iCount = iPayAssessmentService.getTranPayVoEntityCount(countWhere);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }


    //交通补助获取
    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_tran_dept_pdf_list")
    public LayTable<TransportationPayVoEntity> GetSummaryPdfList(HttpServletRequest request) {
        LayTable<TransportationPayVoEntity> layTable = new LayTable<TransportationPayVoEntity>();
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            String year = request.getParameter("year");
            String month = request.getParameter("month");

            String orgid = request.getParameter("orgid");
            String orgsummaryid = request.getParameter("orgsummaryid");
            String realname = request.getParameter("realname");

            String orgs = "";
            List<OrgEntity> orgEntities = new ArrayList<>();
            orgEntities = GetOrgListByOrgid(Long.valueOf(orgid));

            for (OrgEntity orgEntity : orgEntities) {
                if (orgs.equals(""))
                    orgs = String.valueOf(orgEntity.getOrgid());
                else
                    orgs += "," + orgEntity.getOrgid();
            }

            String where = "";
            String countWhere = "";
            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (month != null && month.length() > 0) {
                where += " AND mouth=" + month;
            }

            if (orgs.length() > 0) {
                where += " AND orgid IN (" + orgs + ")";
            }

            if (orgsummaryid != null && orgsummaryid.length() > 0 && !orgsummaryid.equals("0")) {
                where += " AND orgsummaryid=" + orgsummaryid;
            }

            if (realname != null && realname.length() > 0) {
                where += " AND userid IN (SELECT userid FROM t_sys_user WHERE cardno LIKE '%" + realname + "%'  or realname LIKE '%" + realname + "%')";
            }

            countWhere = where;
            int beginrow = (page - 1) * limit;
            int endrow = limit;

            where += " LIMIT " + beginrow + "," + endrow;
            List<TransportationPayVoEntity> lst = iPayAssessmentService.getTranPayVoEntity(where);
            List<TransportationPayVoEntity> exeportlst = new ArrayList<>();
            for (TransportationPayVoEntity payVoEntity : lst) {
                if(payVoEntity.getLostMoney()!=0){
                    exeportlst.add(payVoEntity);
                }
            }

            for (int i = 0; i < exeportlst.size(); i++) {
                exeportlst.get(i).setRowNum(i + 1);
            }

            int iCount = exeportlst.size();
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(exeportlst);//切换为筛选数据

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }


    @ResponseBody
    @RequestMapping(value = "/getPDFData")
    private List<Map> getData(HttpServletRequest request) {
        try {
            Boolean rs = false;
            String type = request.getParameter("type");
            List<Configure> configureList = new ArrayList<>();
            configureList = configureService.getAll(" and  code='jiaotong' and type=" + type);

            if (configureList.size() > 0) {
                Date d = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  ");
                Configure configure = configureList.get(0);

                Date start = sdf.parse(sdf.format(configure.getStarttime()));
                Date end = sdf.parse(sdf.format(configure.getEndtime()));
                Date now = sdf.parse(sdf.format(d));
                if (start.getTime() <= now.getTime() && end.getTime() >= now.getTime()) {

                    rs = true;
                }
            }
            if (!rs) {
                return null;
            }


            int year = Integer.parseInt(request.getParameter("year"));
            int month = Integer.parseInt(request.getParameter("month"));
            String strorgid = this.GetLoginUser().getSzdw().toString();
            String strstatus = "0";
            String where = "";
            where += " AND orgid IN (" + strorgid + ")";

            Calendar cal = Calendar.getInstance();
            int currentyear = cal.get(Calendar.YEAR);
            int currentmonth = cal.get(Calendar.MONTH) + 1;
            if (currentyear != year) {
                currentmonth = 12;
            }

//            if (strorgid != null && strorgid.length() > 0) {
//                OrgEntity orgentity = iOrgService.GetOrgById(Long.parseLong(strorgid));
//                    where += " AND orgid IN ( SELECT orgid FROM t_sys_org WHERE lft>=" + orgentity.getLft() + " AND lft<="
//                        + orgentity.getRgt() + ")";
//            }

            Integer iexit = iOrgSummaryService.GetOrgYearCount("tran", year, 0);
            if (iexit == 0) {
                List<Integer> list = new ArrayList<Integer>();
                for (int i = 0; i < 12; i++) {
                    list.add(i + 1);
                }
                iOrgSummaryService.InsertOrgYearTranBacth(list, year);
            }

            return iOrgSummaryService.GetOrgSummaryTranList(where, year, month, strstatus, currentmonth);
        } catch (
                Exception ex)

        {

        }
        return null;
    }


    @ResponseBody
    @RequestMapping(value = "/createPDF")
    public String uploadBillClient(HttpServletRequest request
    ) {

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码

            byte[] b = decoder.decodeBuffer(request.getParameter("file"));
            String year = request.getParameter("year");
            String month = request.getParameter("month");
            String orgid = this.GetLoginUser().getSzdw().toString();
            for (int i = 0; i < b.length; ++i) {
                // 调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            String fileName = year + "/" + month + "/" + orgid + "/file.pdf";
            String filePath = "/Users/lizeze/Desktop/a/pdf/";


            filePath = ConfigOption.getInstance().getFileurl() + "/jiaotong/";
            fileName = filePath + fileName;


            File file = new File(fileName);
            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            OutputStream out = new FileOutputStream(fileName);
            out.write(b);
            out.flush();
            out.close();
            String webUrl = "http://127.0.0.1:8081/";
            webUrl = ConfigOption.getInstance().getWeburl();
            return webUrl + "jiaotong/" + year + "/" + month + "/" + this.GetLoginUser().getSzdw() + "/file.pdf";
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return "";
        }

    }


    //交通补助修改
    @RequestMapping(value = "/update_tran_pay", method = RequestMethod.POST)
    @ResponseBody
    public ExceResult updateTranPay(@RequestBody TransportationPayList uatmzpdsummary) throws Exception {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        List<TransportationPayVoEntity> payVoEntities = uatmzpdsummary.getAttfjgdlist();
        String tpayid = "";
        try {
            if (payVoEntities.size() > 0) {
                int iResult = iPayAssessmentService.updateTranPayListByid(payVoEntities);
                if (iResult > 0) {
                    result.setCode(200);
                    result.setResult(iResult);
                    result.setMsg("操作成功");
                } else {
                    result.setCode(300);
                    result.setResult(iResult);
                    result.setMsg("操作失败");
                }
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
            ex.printStackTrace();
        }

        return result;
    }

    //交通补助状态改变
    @RequestMapping(value = "/update_tran_pay_status", method = RequestMethod.POST)
    @ResponseBody
    public ExceResult summaryPayUpdate(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String strorgsummaryid = request.getParameter("orgsummaryid");
            String strstatus = request.getParameter("status");

            Long orgsummaryid = Long.parseLong(strorgsummaryid);
            int status = Integer.parseInt(strstatus);

            int iResult = 0;
            iResult = iPayAssessmentService.UpdateTranAttStatus(orgsummaryid, status);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
            ex.printStackTrace();
        }
        return result;
    }
    //endregion

    //交通补助状态改变
    @RequestMapping(value = "/update_tran_pay_statusbm", method = RequestMethod.POST)
    @ResponseBody
    public ExceResult summaryPayUpdatebm(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String strorgsummaryids = request.getParameter("orgsummaryids");
            String strstatus = request.getParameter("status");

            int status = Integer.parseInt(strstatus);
            String orgsummaryids = "(" + strorgsummaryids.substring(0, strorgsummaryids.length() - 1) + ")";

            int iResult = 0;
            iResult = iPayAssessmentService.UpdateTranAttStatusBm(orgsummaryids, status);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
            ex.printStackTrace();
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/export_excel")
    public ExceResult ExportExcel(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String year = request.getParameter("year");
            String mouth = request.getParameter("mouth");
            String orgid = request.getParameter("orgid");
            String orgsummaryid = request.getParameter("orgsummaryid");
            String where = "";
            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (mouth != null && mouth.length() > 0) {
                where += " AND month=" + mouth;
            }
            if (orgid != null && orgid.length() > 0) {
                OrgEntity orgentity = iOrgService.GetOrgById(Long.parseLong(orgid));
                where += " AND orgid IN (SELECT orgid FROM t_sys_org WHERE lft>=" + orgentity.getLft() + " AND lft<="
                        + orgentity.getRgt() + ")";
            } else {
                where += " AND orgid (" + this.GetOrgListByRole() + ")";
            }

            if (orgsummaryid != null && orgsummaryid.length() > 0 && !orgsummaryid.equals("0")) {
                where += " AND orgsummaryid=" + orgsummaryid;
            }

            List<TransportationPayVoEntity> lst = iPayAssessmentService.getTranPayVoEntity(where);
            List<TransportationPayVoEntity> exeportlst = new ArrayList<>();
            for (TransportationPayVoEntity payVoEntity : lst) {
                if(payVoEntity.getLostMoney()!=0){
                    exeportlst.add(payVoEntity);
                }
            }

            for (int i = 0; i < exeportlst.size(); i++) {
                exeportlst.get(i).setRowNum(i + 1);
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

            //String finalXlsxPath=ConfigOption.getInstance().getTemplateurl()+"/kqtemp.xlsx";
            //String filename=ConfigOption.getInstance().getTemplateurl()+"/考勤_"+sdf.format(new Date())+".xlsx";

            String fileName = "jiaotong_" + sdf.format(new Date()) + ".xlsx";
            SubheadModel subheadingVo = new SubheadModel();
            String title = "房山公安分局" + iOrgService.GetOrgById(Long.parseLong(orgid)).getOrgname() + year + "年" + mouth + "月交通补贴";
            subheadingVo.setHeader(title);
            subheadingVo.setSheetName("在职补助表");
            ExportConfig exportConfig = ExportConfigFactory.getConfig("transpay.xml");
            ExportResult exportResult = FileExportor.getExportResult(exportConfig, exeportlst, subheadingVo);//导出处理后数据
            String saveUrl = ConfigOption.getInstance().getFileurl();//服务器缓存地址
            String fileRoute = getSavePath(saveUrl);
            String saveFileUrl = fileRoute + fileName;
            OutputStream outputStream = new FileOutputStream(saveFileUrl);
            exportResult.export(outputStream);

            String url = getSavePath(ConfigOption.getInstance().getWeburl()) + fileName;//增加路径，避免重复，增加效率
            result.setCode(200);
            result.setResult(1);
            result.setMsg(url);

        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/export_excel_all")
    public ExceResult ExportExcelAll(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String year = request.getParameter("year");
            String mouth = request.getParameter("mouth");

            String where = "";
            if (year != null && year.length() > 0) {
                where += " AND year=" + year;
            }
            if (mouth != null && mouth.length() > 0) {
                where += " AND month=" + mouth;
            }


            List<TransportationPayVoEntity> lst = iPayAssessmentService.getTranPayVoEntity(where);
            List<TransportationPayVoEntity> exeportlst = new ArrayList<>();
            for (TransportationPayVoEntity payVoEntity : lst) {
                if(payVoEntity.getLostMoney()!=0){
                    exeportlst.add(payVoEntity);
                }
            }

            for (int i = 0; i < exeportlst.size(); i++) {
                exeportlst.get(i).setRowNum(i + 1);
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");


            String fileName = "jiaotongall_" + sdf.format(new Date()) + ".xlsx";
            SubheadModel subheadingVo = new SubheadModel();
            subheadingVo.setHeader("交通补助表");
            subheadingVo.setSheetName("在职补助表");
            ExportConfig exportConfig = ExportConfigFactory.getConfig("transpay.xml");
            ExportResult exportResult = FileExportor.getExportResult(exportConfig, exeportlst, subheadingVo);//导出筛选后数据
            String saveUrl = ConfigOption.getInstance().getFileurl();//服务器缓存地址
            String fileRoute = getSavePath(saveUrl);
            String saveFileUrl = fileRoute + fileName;
            OutputStream outputStream = new FileOutputStream(saveFileUrl);
            exportResult.export(outputStream);

            String url = getSavePath(ConfigOption.getInstance().getWeburl()) + fileName;//增加路径，避免重复，增加效率
            result.setCode(200);
            result.setResult(1);
            result.setMsg(url);

        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }


    public static String getSavePath(String url) {
//        todo:最好动态获取，改为动态的路径
        String savePath = url + "/" + getYear() + "/" + getMonth() + "/" + getDay() + "/";
        File dirPath = new File(savePath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        return savePath;
    }
}
